package serverSide;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.json.simple.JSONObject;

import static serverSide.Server.*;

import static serverSide.Server.databasePassword;
import static serverSide.Server.databaseUser;
import static serverSide.Server.databaseUrl;

public class SigninController {
	static public JSONObject checkSignin(JSONObject input) {
		String username = (String)input.get(SUBJECT_SIGNIN_KEY_USERNAME);
		String password = (String)input.get(SUBJECT_SIGNIN_KEY_PASSWORD);
		
		JSONObject output = new JSONObject();
		output.put(SUBJECT_KEY, SUBJECT_VALUE_SIGNIN);
		
		boolean isOk = false;
		
		Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
		try {
			con = DriverManager.getConnection(databaseUrl, databaseUser, databasePassword);
            pst = con.prepareStatement("SELECT * FROM "+"player"+" WHERE"+" username='"+username+"' AND password='"+password+"';");
            rs = pst.executeQuery();
            
            if(rs.next())
            	isOk = true;
            
            Statement st = con.createStatement();
            if(isOk)
            	st.executeUpdate("UPDATE player SET status = 1 WHERE Id = "+rs.getInt("id")+" ;");
        } catch (SQLException ex) {
                ex.printStackTrace();
        } finally {		
	            try {
	                if (rs != null)
	                    rs.close();
	                if (pst != null)
	                    pst.close();
	                if (con != null)
	                    con.close();
                } catch (SQLException ex) {
                	ex.printStackTrace();
	            }
	        }
		if(isOk) {
			output.put(SUBJECT_SIGNIN_KEY_ISACCEPTED, SUBJECT_SIGNIN_VALUE_ACCEPTED);
			output.put(SUBJECT_SIGNIN_KEY_USERNAME, username);
			output.put(SUBJECT_SIGNIN_KEY_PASSWORD, password);
		} else
			output.put(SUBJECT_SIGNIN_KEY_ISACCEPTED, SUBJECT_SIGNIN_VALUE_NOTACCEPTED);
		
		return output;
	}
}
